﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using HandlebarsDotNet; 

namespace SX.Utils
{
    /// <summary>
    /// 视图引擎
    /// </summary>
    public static class ViewEngineHelper
    {
        private static IHandlebars _handlebars;
        static ViewEngineHelper()
        {
            var config = new HandlebarsConfiguration()
            {
                FileSystem = new HandlebarsMvcViewEngineFileSystem(),
            };
            _handlebars = Handlebars.Create(config);
            AddHelper(_handlebars);
        }

        static void AddHelper(IHandlebars handlebars)
        {
            handlebars.RegisterHelper("asset", HandlebarHelpers.Asset);
            handlebars.RegisterHelper("date", HandlebarHelpers.Date);
            handlebars.RegisterHelper("tags",
                (writer, context, arguments) => writer.Write("tags:" + string.Join("|", arguments)));
            handlebars.RegisterHelper("encode",
                (writer, context, arguments) => writer.Write("encode:" + string.Join("|", arguments)));
            handlebars.RegisterHelper("url", HandlebarHelpers.Url);
            handlebars.RegisterHelper("excerpt", (writer, context, arguments) => writer.Write("url:" + string.Join("|", arguments)));
        }

        public static void Init() {
            var inits = ReflectionHelper.FindClassesOfType<IHandlebarsInit>();
            foreach (var type in inits)
            {
                if (type.IsClass)
                {
                    var init = Activator.CreateInstance(type) as IHandlebarsInit;
                    init.Init(_handlebars);
                }
            }
        }
        /// <summary>
        /// 创建视图对象
        /// </summary>
        public static HandlebarsMvcView Create(string module, string controlName, string actionName)
        {
            string path;
            if (string.IsNullOrEmpty(module))
            {
                path = ConfigHelper.GetApp("Views", "Views") + "/"
                         + controlName.Replace("Controller", "")
                         + "/" + actionName + ".hbs";
            }
            else
            {
                path = "Modules/"+ module + "/"+ConfigHelper.GetApp("Views", "Views") + "/"
                         + controlName.Replace("Controller", "")
                         + "/" + actionName + ".hbs";
            }
           
            return Create(path);
        }
        /// <summary>
        /// 创建视图对象
        /// </summary>
        /// <param name="path">相对路径，如：/abc/cyq/a.hbs</param>
        public static HandlebarsMvcView Create(string path)
        {
            return new HandlebarsMvcView(path, _handlebars);
            //path = AppDomain.CurrentDomain.BaseDirectory + path.TrimStart('/').Replace("/", "\\");

            //return null;
        } 
    }
}
